package org.ecloud.auth.server.service.impl;

import java.util.concurrent.TimeUnit;

import org.ecloud.auth.server.service.OAuthService;
import org.ecloud.biz.secret.model.SecretPo;
import org.ecloud.biz.secret.service.SecretQueryService;
import org.ecloud.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service("oauthServiceImpl")
public class OAuthServiceImpl implements OAuthService {

	@Autowired
    private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private SecretQueryService SecretQueryService;
	
	@Override
	public void addAuthCode(String authCode, String clientId) {
		redisTemplate.opsForValue().set(authCode, clientId, 10, TimeUnit.MINUTES);
	}

	@Override
	public void removeAuthCode(String authCode) {
		redisTemplate.delete(authCode);
	}

	@Override
	public boolean checkAuthCode(String authCode) {
		return redisTemplate.hasKey(authCode);
	}

	@Override
	public void addAccessToken(String accessToken, String clientId) {
		redisTemplate.opsForValue().set(accessToken, clientId, 10, TimeUnit.MINUTES);
	}

	@Override
	public void removeAccessToken(String accessToken) {
		redisTemplate.delete(accessToken);
	}

	@Override
	public boolean checkAccessToken(String accessToken) {
		return redisTemplate.hasKey(accessToken);
	}

	@Override
	public void addRefreshToken(String refreshToken, String clientId) {
		redisTemplate.opsForValue().set(refreshToken, clientId, 10, TimeUnit.MINUTES);
	}

	@Override
	public void removeRefreshToken(String refreshToken) {
		redisTemplate.delete(refreshToken);
	}

	@Override
	public boolean checkRefreshToken(String refreshToken) {
		return redisTemplate.hasKey(refreshToken);
	}

	@Override
	public String getClientIdByAuthCode(String authCode) {
		if(!checkAuthCode(authCode)){
			return null;
		}
		return redisTemplate.opsForValue().get(authCode).toString();
	}

	@Override
	public String getClientIdByAccessToken(String accessToken) {
		if(!checkAccessToken(accessToken)){
			return null;
		}
		return redisTemplate.opsForValue().get(accessToken).toString();
	}

	@Override
	public String getClientIdByRefreshToken(String refreshToken) {
		if(!checkRefreshToken(refreshToken)){
			return null;
		}
		return redisTemplate.opsForValue().get(refreshToken).toString();
	}

	@Override
	public long getExpireIn() {
		return 1800;
	}

	@Override
	public boolean checkClientId(String clientId) {
		SecretPo po = SecretQueryService.getByKey(clientId);
		return BeanUtil.isNotEmpty(po);
	}

	@Override
	public boolean checkClientSecret(String clientSecret) {
		SecretPo po = SecretQueryService.getBySecret(clientSecret);
		return BeanUtil.isNotEmpty(po);
	}

	@Override
	public boolean checkClientIdSecret(String clientId, String clientSecret) {
		SecretPo po = SecretQueryService.getByKeySecret(clientId, clientSecret);
		return BeanUtil.isNotEmpty(po);
	}

}
